from django.shortcuts import HttpResponse, render, redirect
from app01 import models


# Create your views here.

# index
def index(request):
    """
    :param request: 请求相关对象
    :return: HttpResponse 返回字符串 render 返回html页面 redirect 重定向
    """
    # return HttpResponse("this is HttpResponse, return str")
    # return render(request, 'templates/index.html')  # 返回html网页
    return redirect('https://www.baidu.com')  # 重定向


def login(request):
    # print(request.method)
    # print(request.GET)
    # print(request.GET.get('username'))
    # print(request.GET.getlist('username'))
    if request.method == 'POST':
        username = request.POST.get('username')
        password = request.POST.get('password')
        # filter 查数据
        res = models.User.objects.filter(username=username).first()
        if res:
            if res.password == password:
                return HttpResponse('登录成功')
            else:
                return HttpResponse('登录失败')
        else:
            return HttpResponse('用户不存在')
    return render(request, 'templates/login.html')


def reg(request):
    if request.method == 'POST':
        username = request.POST.get('username')
        password = request.POST.get('password')
        # create 增加数据 返回创建的对象
        # res = models.User.objects.create(username=username,password=password)
        # print(res)
        # 方式二 通过类添加记录
        user_obj = models.User(username=username, password=password)
        user_obj.save()  # 保存数据
    return render(request, 'templates/reg.html')


def userlist(request):
    res = models.User.objects.all()
    print(res)
    return render(request, 'templates/userlist.html', locals())


def edit(request):
    user_id = request.GET.get('user_id')
    print(user_id)
    edit_obj = models.User.objects.filter(id=user_id).first()
    if request.method == 'POST':
        username = request.POST.get('username')
        password = request.POST.get('password')
        # 修改数据 方式1
        models.User.objects.filter(id=user_id).update(username=username, password=password)
        # # 方式二
        # edit_obj.username = username
        # edit_obj.password = password
        # edit_obj.save()
        # 展示页面
        return redirect('/userlist/')
    return render(request, 'templates/edit.html', locals())


def delete(request):
    user_id = request.GET.get('user_id')
    print(user_id)
    models.User.objects.filter(id=user_id).delete()
    return redirect('/userlist/')


def test(request):
    return HttpResponse("app01 test")


from django.http import JsonResponse


def serialize(request):
    user_dic = {'name': '卡卡', 'age': 18, 'addr': '北京'}
    l = [1, 2, 3, 4]
    # JsonResponse自动将对象序列化返回 {'ensure_ascii': False} 让中文不转码
    # return JsonResponse(user_dic, json_dumps_params={'ensure_ascii': False})

    # 报错不允许非字典对象序列化，需要设置为安全
    return JsonResponse(l, safe=False)


def upload(request):
    if request.method == 'POST':
        print(request.POST)  # 只能获取POST中的键值对
        print(request.FILES)  # 获取文件
        file_obj = request.FILES.get('file')
        with open(file_obj.name, 'wb') as f:
            for line in file_obj.chunks():  # 推荐加上chunks方法
                f.write(line)
    return render(request, 'templates/form.html')


# 序列化组件
from django.http import HttpResponse
from django.core import serializers


def ab_json(request):
    user_queryset = models.User.objects.all()
    res = serializers.serialize('json', user_queryset)
    return HttpResponse(res)
    # return render(request,'templates/ ab_json.html',locals())

# 批量插入
def batch_insert(request):
    # 效率低
    # for i in range(1000):
    #     models.User.objects.create(username=f'第{i}个人')
    # user_queryset=models.User.objects.all()

    # bulk_create效率高
    # user_list = []
    # for i in range(1000):
    #     user_obj=models.User(username=f'第{i}个人')
    #     user_list.append(user_obj)
    # models.User.objects.bulk_create(user_list)

    # 分页
    # 想访问哪页
    # 每页展示多少条
    # q

    user_queryset=models.User.objects.all()
    return render(request,'templates/batch_insert.html',locals())
